package CCN::CallWeaver::probe;
# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net/
#
use strict; use warnings;

sub peers()
{
    return (
        {
            peer_name => 'sip1',
        },
        {
            peer_name => 'sip2',
        },
    )
}

sub callroutes()
{
    my @targets = targets();
    foreach (@targets)
    {
        $_->{callroutes} = _callroutes_of($_->{cr_name});
    }
    return @targets;
}

use JSON;

sub get_json($)
{
    my $name = shift;
    open(my $fh, '<', "$configuration::html_base/config/$name.json") or 
        return jsonToObj('');
    local $/; # slurp mode
    my $json = jsonToObj(<$fh>);
    close($fh);
    return $json;
}

our $targets;

sub targets()
{
    return @{$targets} if defined $targets;

    my $sip_json = get_json('sip');
    my $card_json = get_json('cards');
    my @ts_groups = ();

    my $tdmv_id = 0;
    for my $k (sort keys %{$card_json})
    {
        next unless $k =~ /^tsg_(\d+)_(\d+)_signaling_type$/;

        my $port = $1;
        my $ts   = $2;

        next if lc($card_json->{"port_${port}_fe_media"}) eq 'unused';
        next unless $card_json->{$k} =~ /^(pri|cas)$/;

        $tdmv_id ++;

        push @ts_groups,
        {
            cr_name => "tsg_${port}_${ts}",
            cr_description => "Port ${port} Timeslot Group ${ts}",
            cr_source => 'g'.$tdmv_id,
            cr_dial => 'Zap/g'.$tdmv_id,
        }
    }

    my @sip_peers = ();
    for my $k (keys %{$sip_json})
    {
        next unless $k =~ /^(\w+)_mode$/;
        
        my $peer = $1;

        next unless defined $sip_json->{$k} and $sip_json->{$k} ne '';
        next if lc($sip_json->{$k}) eq 'unused';

        push @sip_peers,
        {
            cr_name => $peer,
            cr_description => "VoIP Peer $peer",
            cr_source => $peer,
            cr_dial => 'SIP/'.$peer,
        }
    }

    $targets = [@ts_groups,@sip_peers];
    return @{$targets};
}

sub _callroutes_names()
{
    return qw(A B);
}

sub _callroutes_of($)
{
    my $w = shift;
    my @targets = targets();
    return [
        map {
            { callroute => "${w}_$_", callroute_name => $_, targets => \@targets }
        } _callroutes_names(),
    ];
}

1;